/**
 * 格式化数字
 * @param value 要格式化的数字
 * @param digitsInfo {小数点前最小位数}.{小数点后最小位数}-{小数点后最大位数}
 */
export function decimal(
  value: number | string | null | undefined,
  digitsInfo = '1.2-2',
  separator = ','
) {
  value = Number(value)
  if (Number.isNaN(value)) {
    return 'NaN'
  }

  const arr = /(\d+)\.(\d+)-(\d+)/.exec(digitsInfo)
  const minInteger = +arr![1]
  const minFraction = +arr![2]
  const maxFraction = +arr![3]

  const [int, fra] = value.toFixed(maxFraction).split('.')

  const list = int.padStart(minInteger, '0').split('')
  for (let i = list.length - 3; i > 0; i -= 3) {
    list.splice(i, 0, separator)
  }

  const tail = (fra || '').replace(/0*$/, '').padEnd(minFraction, '0')

  return list.join('') + (tail && '.' + tail)
}

export function thousand(value: number | string | null | undefined) {
  if (value === null || value === undefined) {
    return ''
  }
  return decimal(value)
}
